package com.xh.core.util;

import javax.servlet.http.HttpServletRequest;

/*
 * @Author daiwei
 * @Description
 * @Date 2018/10/30 17:28
 **/
public class IPUtils {

    /**
     * 获取客户端请求IP地址
     * @param request
     * @return
     */
    public static String getIp(final HttpServletRequest request) {
        String ip;
        ip = request.getHeader("X-Forword-For");
        if (ip == null || ip.trim().equals("") || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }else if (ip == null || ip.trim().equals("") || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }else if (ip == null || ip.trim().equals("") || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }else if (ip == null || ip.trim().equals("") || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }else if (ip == null || ip.trim().equals("") || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }

        /* 多个路由时，取第一个非unknown的ip */
        if (ip != null && !ip.trim().equals("")) {
            if (ip.indexOf(',') > 0) {
                ip = ip.substring(0, ip.indexOf(','));
            }
            return ip;
        } else {
            return "0.0.0.0";
        }
    }

    /**
     * 将127.0.0.1形式的IP地址转换成十进制整数
     * @param strIp
     * @return
     */
    public static long ip2long(final String strIp) {
        final long[] ip = new long[4];
        final int position1 = strIp.indexOf('.');
        final int position2 = strIp.indexOf('.', position1 + 1);
        final int position3 = strIp.indexOf('.', position2 + 1);


        ip[0] = Long.parseLong(strIp.substring(0, position1));
        ip[1] = Long.parseLong(strIp.substring(position1 + 1, position2));
        ip[2] = Long.parseLong(strIp.substring(position2 + 1, position3));
        ip[3] = Long.parseLong(strIp.substring(position3 + 1));


        return (ip[0] << 24) + (ip[1] << 16) + (ip[2] << 8) + ip[3];
    }
}
